package com.hu.lsp.Test;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @Author lsp
 * @Date 2020/8/27 13:26
 * @Version 1.0
 */
@Slf4j
public class ListDistinctTest {

    public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        System.out.println("这个函数将应用到每一个item");
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

    public static void main(String[] args) {
        List<PenBean> penBeanList = new ArrayList<PenBean>();
        penBeanList.add(new PenBean("铅笔","black"));
        penBeanList.add(new PenBean("铅笔","white"));
        penBeanList.add(new PenBean("铅笔","black"));
        penBeanList.add(new PenBean("中性笔","white"));
        penBeanList.add(new PenBean("中性笔","white"));
       // List<PenBean> newPenBeanList=penBeanList.stream().distinct().collect(Collectors.toList());
       // List<PenBean> newPenBeanList=penBeanList.stream().filter(distinctByKey())
        List<PenBean> newPenBeanList = penBeanList.stream().filter(distinctByKey((p) -> (p.getColor()))).collect(Collectors.toList());


        newPenBeanList.forEach(n->{
            System.out.println(n.getColor());
            System.out.println(n.getType());
        });

    }
}
